package com.mes.cloud.util;

import com.mes.cloud.enums.ValidatorClassEnum;

import java.lang.reflect.Method;

public class StrategyFactory {
    private StrategyFactory(){
    }
    private static volatile StrategyFactory factory = null;
    public static StrategyFactory getInstance(){
        if (factory==null){
                synchronized (StrategyFactory.class){
                    factory = new StrategyFactory();
                }
        }
        return factory;
    }
    public  Object getStrategy(String strategyType) throws Exception {
        String className = ValidatorClassEnum.getDesc(strategyType.trim());
        if (StringUtils.isEmpty(className)){
             throw new Exception("参数异常");
        }
        return  Class.forName(className).newInstance();
    }
    public boolean validatorInvoke(String type, Object o) throws Exception {
        String methodName = type.toLowerCase();
        boolean flage = false;
        try {
            Object ob = getStrategy(type);
            Method[] methods = ob.getClass().getDeclaredMethods();
            for (Method method : methods) {
                if (method.getName().equals(methodName)) {
                    Method s = ob.getClass().getMethod(methodName, method.getParameterTypes());
                    flage  = (boolean) s.invoke(ob,type,o);
                    break;
                }
            }
        }catch (Exception e){
            throw new Exception("参数异常");
        }
        return flage;
    }
} 